package com.gblfy.controller;

import com.gblfy.dao.OrderResposity;
import com.gblfy.entity.Order;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderResposity orderResposity;
    
    //http://localhost:8000/order/create?productId=11&userId=11222
    @GlobalTransactional(timeoutMills = 300000, name = "spring-cloud-demo-tx")
    @GetMapping("/order/create")
    public String createOrder(Integer productId, Integer userId) {

        Order order = new Order();
        order.setProductId(productId);
        order.setUserId(userId);
        orderResposity.save(order);
        String result = restTemplate.getForObject("http://stock-serv/stock/reduce/" + productId, String.class);
        if (!result.equals("success")) {
            throw new RuntimeException();
        }
        return result;
    }
}
